import { Table,Button,Modal, Tree } from 'antd'
import React, { useEffect, useState } from 'react'
import axios from 'axios'
import {DeleteOutlined,EditOutlined,ExclamationCircleOutlined} from '@ant-design/icons'

const {confirm} = Modal

export default function RoleList() {
  const [dataSource,setdataSource] = useState([])
  const [rightList,setRightList] = useState([])
  const [currentRights,setcurrentRights] = useState([])
  const [currentId,setcurrentId] = useState(0)
  const [refresh,setrefresh] = useState(false)
  const [isModalOpen,setisModalOpen] = useState(false)

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      // 定义样式用render是一个函数
      render:(id)=>{
        return <b>{id}</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'roleName'
    },
    {
      title: '操作',
      render:(item)=>{
        return <div>
           <Button danger shape='round' icon={<DeleteOutlined />} onClick={()=>confirmMethod(item)}></Button>
           <Button type="primary" shape='round' icon={<EditOutlined />} onClick={()=>{
            setisModalOpen(true)
            setcurrentRights(item.rights)
            setcurrentId(item.id)
           }}></Button>
        </div>
      }
    },
  ]

  const confirmMethod= (item)=>{
    confirm({
      title: '你确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      // content: 'Some descriptions',
      onOk() {
        // console.log('OK');
        deleteMethod(item)
      },
      onCancel() {
        // console.log('Cancel');
      },
    });
  }
//点击删除执行此方法 (在操作项中传入形参拿到点击删除时的数据)
  const deleteMethod = (item)=>{
    // console.log(item);
    //删除后要当前页面同步状态 + 后端数据也要同步
    setdataSource(dataSource.filter(data=>data.id!==item.id)) //页面状态（用.filter()过滤即可
    axios.delete(`http://localhost:5000/roles/${item.id}`)   //请求delete删除后端数据
  }

  useEffect(()=>{
    axios.get("http://localhost:5000/roles").then(res=>{
      // console.log(res.data);
      setdataSource(res.data)
    })
  },[])

  useEffect(()=>{
    axios.get("http://localhost:5000/rights?_embed=children").then(res=>{
      // console.log(res.data);
      setRightList(res.data)
    })
  },[refresh])

//点击确认 成功
  const handleOk = ()=>{
    // console.log(currentRights);
    setisModalOpen(false)
    //同步dataSource
    setdataSource(dataSource.map(item=>{
      // 判断item.id和正在分配权限的ID对比，如果相等就展开然后新的覆盖上去；不相等直接return
      if(item.id===currentId){
        return {
          ...item,
          rights:currentRights
        }
      }
      return item
    }))
    //patch补丁更新回后端数据中
    axios.patch(`http://localhost:5000/roles/${currentId}`,{
      rights:currentRights
    })
    .then(setrefresh)
    .catch((e)=>console.log(e))
  }
  //失败
  const handleCancel = ()=>{
    setisModalOpen(false)
  }

  const onCheck = (checkKeys)=>{
    // console.log(checkKeys);
    setcurrentRights(checkKeys.checked)
  }
  return (
    <div>
      {/* 后端返回的数据中没有key值，使用rowKey方法指定key */}
      <Table dataSource={dataSource} columns={columns} rowKey={(item)=>item.id}></Table>

      <Modal title="权限分配" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Tree checkable
         treeData={rightList}
         checkedKeys={currentRights}
         checkStrictly={true}
         onCheck={onCheck}
         ></Tree>
      </Modal>
    </div>
  )
}
